import java.util.HashMap;
import java.util.List;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleWeightedGraph;

import cytoscape.CyEdge;
import cytoscape.CyNetwork;
import cytoscape.CyNode;

/**
 * Build a graph according to a cytoscape network uploaded by user.
 * Replaces initNet() from PluginCore.
 * @author odedmagg
 *
 */
@SuppressWarnings("unchecked")
public class CytoscapeNetFactory {
	static SimpleWeightedGraph<String, DefaultWeightedEdge> generate(
			HashMap<String, Gene> outGeneMap, CyNetwork cyNet) throws Exception {
	if (outGeneMap == null) {
		System.err.println("PARFAIT error: CytoscapeNetFactory.generate() received null outGeneMap parameter.");
		return null;
	}
		
	Class<DefaultWeightedEdge> myclass = DefaultWeightedEdge.class;
	SimpleWeightedGraph<String, DefaultWeightedEdge> net = 
		new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
	
	List<CyNode> nodes = cyNet.nodesList();
	List<CyEdge> edges = cyNet.edgesList();

	if ((nodes.size() == 0) && (edges.size() == 0)) {
		GUIException.displayErrorMessage("Plese upload a network into cytoscape");
	}
	String edgeStr, prot1, prot2, doubleStr;
	double prob;
	int ind1, ind2;
	for (CyNode node: nodes) {
		String currGeneName = node.getIdentifier();
		boolean wasAdded = net.addVertex(currGeneName);
		if (wasAdded) {
			outGeneMap.put(currGeneName, new Gene(currGeneName, node.getRootGraphIndex()));
		}
	}
	for (CyEdge edge: edges) {
		edgeStr = edge.getIdentifier();
		ind1 = edgeStr.indexOf(" ((");
		ind2 = edgeStr.indexOf(")) ");
		if ((ind1== -1) || (ind2==-1)) {
			throw new Exception("Error with edges.");
		}
		prot1 = edgeStr.substring(0,ind1);
		doubleStr = edgeStr.substring(ind1+3, ind2);
		prob = Double.parseDouble(doubleStr);
		prot2 = edgeStr.substring(ind2+3, edgeStr.length());
		
		DefaultWeightedEdge e = net.addEdge(prot1, prot2);
		net.setEdgeWeight(e, prob);
	}


	return net;
	}
}
